﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using 凯蒽斯.Dto;
using 凯蒽斯.Help;
using 凯蒽斯.page;

namespace 凯蒽斯
{
   

    public partial class MainWindow : Window
    {
        private readonly DispatcherTimer _timer = new DispatcherTimer();
        
        public static List<ModbusSetting> modbusSettings;
        public static ModbusHelp modbusHelp;

        public static Dictionary<string,object> valuePairs = new Dictionary<string, object>();
        public MainWindow()
        {
            
            modbusHelp = new ModbusHelp("192.168.1.40");
            modbusHelp.ConnectAsync().Wait();
            modbusSettings = SqlHelp.Db.Queryable<ModbusSetting>().ToListAsync().Result;
            this.Left = 10;
            this.Top = 10;
            InitializeComponent();
            // 配置定时器：间隔1秒（根据需求调整，如500ms）
            _timer.Interval = TimeSpan.FromSeconds(1);
            // 绑定定时器触发事件（循环读取的核心）
            _timer.Tick += async (s, e) => await Timer_TickAsync();
            _timer.Start();
        }


        // 所有按钮共用的点击事件
        private void Button_Navigate(object sender, RoutedEventArgs e)
            {
                // 将 sender 转换为 Button，获取其 Tag 属性（存储页面路径）
                if (sender is Button btn && !string.IsNullOrEmpty(btn.Tag?.ToString()))
                {
                    string pageUri = btn.Tag.ToString();
                    NavigateToPage(pageUri); // 调用通用导航方法
                }
            }
            private void NavigateToPage(string pageUri)
            {
                if (string.IsNullOrEmpty(pageUri)) return;

                try
                {
                    frameMain.Source = new Uri(pageUri, UriKind.Relative);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"页面加载失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        #region 定时器相关方法
        // 在这里编写每次定时器触发时要执行的异步操作
        //根据数据库中的配置循环读取数据
        //并且根据Description存储到字典中
        private async Task Timer_TickAsync()
        {
            
            foreach (var setting in modbusSettings)
            {
                switch (setting.FunctionCode)
                {
                    case 1:
                        if (valuePairs.ContainsKey(setting.Description))
                        {
                            // 键已存在，更新值
                            valuePairs[setting.Description] = await modbusHelp.ReadCoilsAsync(Convert.ToByte(setting.unitId),Convert.ToUInt16(setting.startAddress),Convert.ToUInt16(setting.count));
                        }
                        else
                        {
                            // 键不存在，添加新键值对
                            valuePairs.Add(setting.Description, await modbusHelp.ReadCoilsAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count));
                        }
                        break;
                    case 2:
                        if (valuePairs.ContainsKey(setting.Description))
                        {
                            // 键已存在，更新值
                            valuePairs[setting.Description] = await modbusHelp.ReadInputsAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count);
                        }
                        else
                        {
                            // 键不存在，添加新键值对
                            valuePairs.Add(setting.Description, await modbusHelp.ReadInputsAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count));
                        }
                        
                        break;
                    case 3:
                        if (valuePairs.ContainsKey(setting.Description))
                        {
                            if (new[] { 0, 1, 2, 3, 6, 7 }.Contains((int)setting.PlcType))
                            {
                                // 显式指定TResult为Int64
                                valuePairs[setting.Description] = PlcTypeHelp.ConvertTo<Int64>(
                                    await modbusHelp.ReadHoldingRegistersAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count), (int)setting.PlcType);
                            }
                            else if (new[] { 4, 5 }.Contains((int)setting.PlcType))
                            {
                                // 显式指定TResult为double
                                valuePairs[setting.Description] = PlcTypeHelp.ConvertTo<double>(
                                    await modbusHelp.ReadHoldingRegistersAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count), (int)setting.PlcType);
                            }
                        }
                        else
                        {
                            if (new[] { 0, 1, 2, 6, 7 }.Contains((int)setting.PlcType))
                            {
                                // 键不存在，添加新键值对
                                valuePairs.Add(setting.Description,PlcTypeHelp.ConvertTo<Int64>(
                                    await modbusHelp.ReadHoldingRegistersAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count), (int)setting.PlcType));
                            }
                            else if (new[] { 4, 5 }.Contains((int)setting.PlcType))
                            {
                                // 键不存在，添加新键值对
                                valuePairs.Add(setting.Description, PlcTypeHelp.ConvertTo<double>(
                                    await modbusHelp.ReadHoldingRegistersAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count), (int)setting.PlcType));
                            }
                            
                        }
                        
                        break;
                    case 4:
                        if (valuePairs.ContainsKey(setting.Description))
                        {
                            // 键已存在，更新值
                            valuePairs[setting.Description] = await modbusHelp.ReadInputRegistersAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count);
                        }
                        else
                        {
                            // 键不存在，添加新键值对
                            valuePairs.Add(setting.Description, await modbusHelp.ReadInputRegistersAsync((byte)setting.unitId, (ushort)setting.startAddress, (ushort)setting.count));
                        }
                        break;
                }
            }
        }
        #endregion

        public static void messageInvoke(string message)
        {
            MessageBox.Show(message);
        }
        private void Login_Click(object sender, RoutedEventArgs e)
        {

            Login loginWindow = new Login();
            // 订阅登录窗口的“登录成功”事件
            loginWindow.LoginSuccess += EnableFunctionButtons;
            loginWindow.Show();
        }
        private void EnableFunctionButtons()
        {
            AxisBloc.IsEnabled = true;
            RangeSettings.IsEnabled = true;
            AxisSetting.IsEnabled = true;
        }
        private void Logout_Click(object sender, RoutedEventArgs e)
        {
            AxisBloc.IsEnabled = false;
            RangeSettings.IsEnabled = false;
            AxisSetting.IsEnabled = false;
        }
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _timer.Stop();


        }
    }
}